package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl
        extends ServiceImpl<SpecGroupMapper, SpecGroup>
        implements SpecGroupService {


    @Override
    public List<SpecGroupDTO> queryGroupListByCategoryId(Long id) {
        return SpecGroupDTO.convertEntityList(
                this.query().eq("category_id", id).list()
        );
    }


    @Autowired
    private SpecParamService paramService;

    @Override
    public List<SpecGroupDTO> querySpecListByCategoryId(Long categoryId) {
        List<SpecGroupDTO> groupList = SpecGroupDTO.convertEntityList(
                this.query()
                        .eq("category_id", categoryId)
                        .list()
        );

        if (CollectionUtils.isEmpty(groupList)) {
            throw new LyException(404, "该分类下的规格组不存在！");
        }

        // 查询规格参数
        List<SpecParamDTO> paramList = paramService.querySpecParams(categoryId, null, null);

        Map<Long, List<SpecParamDTO>> map = paramList.stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        for (SpecGroupDTO groupDTO : groupList) {
            groupDTO.setParams(map.get(groupDTO.getId()));
        }

        return groupList;
    }

    @Override
    public void addSpecGroup(SpecGroup specGroup) {
        this.save(specGroup);
    }

    @Override
    public void updateGroup(SpecGroup specGroup) {
        this.updateById(specGroup);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteGroupById(Long id) {
        paramService.remove(
                new QueryWrapper<SpecParam>().eq("group_id", id)
        );
        this.removeById(id);

    }
}
